//导入uuid模块
const uuid = require('node-uuid')
const multer = require('multer')
const fs = require('fs')
//导入数据库操作模块
const db = require("../../db/index")
const path = require("path")
// 格式化时间
var moment = require('moment')

/**
 * 增加申请
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.addApplication = [multer({
    dest: './public/upload/resume',
    limits: {
        fileSize: 8000 * 1000,
        files: 5
    }, filename: function (req, file, cb) {
        var changedName = (new Date().getTime()) + '-' + file.originalname;
        cb(null, changedName);
    }, onError: function (err, next) {
        if (err) {
            return res.send({
                code: 500,
                msg: '文件上传发送了错误！' + err.message,
                data: {}
            })
        } else {
            next(err);
        }
    }
}).any(), (req, res) => {
    const Application = req.body;
    if (JSON.stringify(Application) == "{}") {
        console.log('【增加申请发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Application.title || !Application.name || !Application.major || !Application.contact) {
            // console.log(Application)
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }

    // console.log('Application===>', Application)
    const ip = req.ip
    console.log(Application.name + '提交申请,ip=====>', ip)
    // //生成uuid
    // let uuid1 = uuid.v1();
    // // 去除横线-
    // uuid1 = uuid1.replace(/-/g, '');
    // // 添加id
    // Application['id'] = uuid1;
    //发布时间
    let nowTime = new Date()
    var formatTime = moment(nowTime).format('YYYY-MM-DD HH:mm')
    console.log('申请时间', formatTime)
    Application['apply_time'] = formatTime;
    //该事件是否已存在
    const findSql = 'SELECT * FROM xks_application WHERE title = ? AND name = ? AND class = ? AND contact = ?'
    db.query(findSql, [Application.title, Application.name, Application.class, Application.contact], (err, results) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (results.length > 0) {
            return res.send({
                code: 400,
                msg: '请不要重复提交！',
                data: {}
            })
        }
        let url = '';
        // console.log('文件：' + req.files[0])
        if (null == req.files[0]) url = '无'
        else {
            if (req.files.length > 1) {
                // console.log(req.files)
                for (let i = 0; i < req.files.length; i++) {
                    // console.log(req.files[i].mimetype, req.files[i].fieldname)
                    let oldName = req.files[i].path;//获取名字
                    //给新名字加上原来的后缀
                    let newName = req.files[i].path + path.parse(req.files[i].originalname).ext;
                    fs.renameSync(oldName, newName);//改图片的名字
                    if (i != req.files.length - 1) url = url + "http://localhost:8081/upload/resume/" + req.files[i].filename + path.parse(req.files[i].originalname).ext + ','
                    else url = url + "http://localhost:8081/upload/resume/" + req.files[i].filename + path.parse(req.files[i].originalname).ext
                }
            } else {
                // console.log(req.files)
                let oldName = req.files[0].path;//获取名字
                //给新名字加上原来的后缀
                let newName = req.files[0].path + path.parse(req.files[0].originalname).ext;
                fs.renameSync(oldName, newName);//改图片的名字
                url = "http://localhost:8081/upload/resume/" + req.files[0].filename + path.parse(req.files[0].originalname).ext//该图片的预览路径
            }
        }
        Application['other'] = url
        // console.log(Application)
        // console.log('Application===>', Application)
        const addSql = `INSERT INTO xks_application SET ? `
        db.query(addSql, Application, (err, result) => {
            if (err) {
                console.log(err.message)
                return res.send({
                    code: 505,
                    msg: err.message,
                    data: {}
                })
            }
            if (result.affectedRows !== 1) {
                return res.send({
                    code: 500,
                    msg: '增加失败，请稍后再试！',
                    data: {}
                })
            }
            res.send({
                code: 200,
                msg: '增加成功',
                data: {}
            })
        })
    })
}
]